import React, { useState, useEffect, useCallback } from 'react';
import { Card, Row, Col, Statistic, Table, Tag, Typography, Spin, Alert, Button } from 'antd';
import {
  ArrowUpOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  DollarOutlined,
  GiftOutlined,
  EyeOutlined,
  RiseOutlined,
} from '@ant-design/icons';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import api from '../utils/api';
import dayjs from 'dayjs';
import { getErrorMessage, getSuccessMessage, getHttpErrorMessage, PAGES, ERROR_TYPES, SUCCESS_TYPES } from '../utils/i18n';

const { Title, Text } = Typography;

const Dashboard = () => {
  const [stats, setStats] = useState({
    totalOrders: 0,
    totalRevenue: 0,
    totalUsers: 0,
    activeCoupons: 0,
    growth: {
      orders: 0,
      revenue: 0,
      users: 0,
    },
  });
  const [recentOrders, setRecentOrders] = useState([]);
  const [revenueTrend, setRevenueTrend] = useState([]);
  const [categoryData, setCategoryData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchDashboardData = useCallback(async () => {
    try {
      setLoading(true);
      const [statsRes, ordersRes, trendsRes, categoriesRes] = await Promise.all([
        api.get('/admin/dashboard/stats'),
        api.get('/admin/dashboard/recent-orders'),
        api.get('/admin/dashboard/revenue-trends'),
        api.get('/admin/dashboard/category-distribution'),
      ]);

      // 确保数据结构正确 - 后端返回 {success: true, data: {...}}
      const statsData = statsRes.data?.data || {};
      setStats({
        totalOrders: statsData.orderTotal || 0,
        totalRevenue: statsData.revenueTrend?.reduce((sum, item) => sum + (item.amount || 0), 0) || 0,
        totalUsers: statsData.userTotal || 0,
        activeCoupons: statsData.couponStats?.total || 0,
        growth: {
          orders: 12.5, // 临时硬编码，后续可从API获取
          revenue: 8.3,
          users: 15.2,
        },
      });
      setRecentOrders(Array.isArray(ordersRes.data?.data) ? ordersRes.data.data : []);
      setRevenueTrend(Array.isArray(trendsRes.data?.data) ? trendsRes.data.data : []);
      setCategoryData(Array.isArray(categoriesRes.data?.data) ? categoriesRes.data.data : []);
      setError(null);
    } catch (err) {
      setError(getErrorMessage(PAGES.DASHBOARD, ERROR_TYPES.LOAD_FAILED));
      console.error('Dashboard data fetch error:', err);
      // 设置默认数据以防止渲染错误
      setStats({
        totalOrders: 0,
        totalRevenue: 0,
        totalUsers: 0,
        activeCoupons: 0,
        growth: {
          orders: 0,
          revenue: 0,
          users: 0,
        },
      });
      setRecentOrders([]);
      setRevenueTrend([]);
      setCategoryData([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchDashboardData();
  }, [fetchDashboardData]);

  const getStatusColor = (status) => {
    const colors = {
      completed: 'success',
      pending: 'warning',
      processing: 'processing',
      cancelled: 'error',
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status) => {
    const texts = {
      completed: '已完成',
      pending: '待处理',
      processing: '处理中',
      cancelled: '已取消',
    };
    return texts[status] || status;
  };

  const orderColumns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
      width: 180,
      resizable: true,
      render: (text) => <Text strong>{text}</Text>,
    },
    {
      title: '客户',
      dataIndex: 'customer',
      key: 'customer',
      width: 120,
      resizable: true,
      render: (customer) => (
        <>
          <UserOutlined style={{ marginRight: 8 }} />
          {customer.name}
        </>
      ),
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 100,
      resizable: true,
      render: (amount) => <Text strong>¥{amount.toFixed(2)}</Text>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      resizable: true,
      render: (status) => (
        <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
      ),
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      width: 150,
      resizable: true,
      render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      resizable: true,
      render: () => (
        <Button type="link" icon={<EyeOutlined />} size="small">
          查看
        </Button>
      ),
    },
  ];

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: '24px' }}>
        <Alert
          message={getErrorMessage(PAGES.DASHBOARD, ERROR_TYPES.LOAD_FAILED)}
          description={error}
          type="error"
          showIcon
          action={
            <Button size="small" danger onClick={fetchDashboardData}>
              重试
            </Button>
          }
        />
      </div>
    );
  }

  return (
    <div style={{ backgroundColor: '#f5f5f5', minHeight: '100vh', padding: '24px' }}>
      <div style={{
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        borderRadius: '12px',
        padding: '24px',
        marginBottom: '24px',
        boxShadow: '0 4px 20px rgba(0,0,0,0.1)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div style={{
            width: '48px',
            height: '48px',
            borderRadius: '12px',
            backgroundColor: 'rgba(255,255,255,0.2)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '24px',
            color: 'white'
          }}>
            📊
          </div>
          <div>
            <Title level={2} style={{ color: 'white', margin: 0, fontSize: '28px', fontWeight: '600' }}>
              仪表盘
            </Title>
            <div style={{ color: 'rgba(255,255,255,0.8)', fontSize: '14px', marginTop: '4px' }}>
              实时监控业务数据和运营状况
            </div>
          </div>
        </div>
      </div>

      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} lg={6}>
          <Card hoverable style={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
            <Statistic
              title="总订单数"
              value={stats.totalOrders}
              valueStyle={{ color: '#667eea', fontSize: '24px', fontWeight: '600' }}
              prefix={<ShoppingCartOutlined />}
            />
            <Text style={{ color: '#666', fontSize: '12px' }}>
              <ArrowUpOutlined style={{ color: '#27ae60' }} />
              较上月增长 {stats.growth.orders}%
            </Text>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card hoverable style={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
            <Statistic
              title="总收入"
              value={stats.totalRevenue}
              precision={2}
              valueStyle={{ color: '#11998e', fontSize: '24px', fontWeight: '600' }}
              prefix={<DollarOutlined />}
            />
            <Text style={{ color: '#666', fontSize: '12px' }}>
              <ArrowUpOutlined style={{ color: '#27ae60' }} />
              较上月增长 {stats.growth.revenue}%
            </Text>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card hoverable style={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
            <Statistic
              title="用户总数"
              value={stats.totalUsers}
              valueStyle={{ color: '#f093fb', fontSize: '24px', fontWeight: '600' }}
              prefix={<UserOutlined />}
            />
            <Text style={{ color: '#666', fontSize: '12px' }}>
              <ArrowUpOutlined style={{ color: '#27ae60' }} />
              较上月增长 {stats.growth.users}%
            </Text>
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card hoverable style={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
            <Statistic
              title="活跃优惠券"
              value={stats.activeCoupons}
              valueStyle={{ color: '#ffa726', fontSize: '24px', fontWeight: '600' }}
              prefix={<GiftOutlined />}
            />
             <Text style={{ color: '#666', fontSize: '12px' }}>本月新增 {stats.newCoupons} 张</Text>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} lg={16}>
          <Card title={<Title level={4}>收入趋势</Title>} hoverable style={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={revenueTrend}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Line type="monotone" dataKey="revenue" stroke="#1890ff" strokeWidth={3} />
              </LineChart>
            </ResponsiveContainer>
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card title={<Title level={4}>销售分类</Title>} hoverable style={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie data={categoryData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={80} fill="#8884d8" label>
                  {categoryData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </Card>
        </Col>
      </Row>

      <Card
        title={<Title level={4}>最近订单</Title>}
        hoverable
        style={{ borderRadius: '12px', border: 'none', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}
        extra={
          <Button type="primary" icon={<RiseOutlined />}>
            查看全部
          </Button>
        }
      >
        <Table columns={orderColumns} dataSource={recentOrders} pagination={false} rowKey="id" size="middle" />
      </Card>
    </div>
  );
};

export default Dashboard;